using Microsoft.AspNetCore.Mvc;     // 因为ControllerBase等需要引入
using MyWebApi.Api.Entity;      // 因为Users表需要引入
using System.Collections.Generic;   // 因为泛型需要引入
using System.Linq;     // 因为Where 引入之后我们可以使用一种类似SQL的语法来查询任何形式的数据
using System;
using MyWebApi.Api.Repository;
using MyWebApi.Api.ParamModel;
using MyWebApi.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace MyWebApi.Api.Controllers
{
    // 特性
    // [Authorize]  // [Authorize]下的所有Api接口如：查询、删除、创建用户不能匿名访问，需要Token令牌才可访问
    [ApiController]
    [Route("[controller]")]

    public class PersonalDetailsController : ControllerBase
    {

        // 实例化数据库
        // private MyWebApi.Api.Db.MyWebApiDb db = new Db.MyWebApiDb();

        // 定义为IRepository<T>的泛型接口未知数 T 为 users
        private IRepository<users> _usersRespository;   // 现在_usersRespository里包含IRepository<T>泛型接口里面的属性(可以使用这些属性来进行对Users表的操作)
        private IRepository<supplier> _supplier;
        private IRepository<personal_details> _personal_details;
        private IRepository<receiving_site> _receiving_site;
        private IRepository<shopping_cart> _shopping_cart;

        private TokenParameter _tokenParameter;

        private readonly IConfiguration _configuration;


        // 一个构造函数：初始化UsersController控制器，使该控制器一开始就有以下的属性
        public PersonalDetailsController(IConfiguration configuration,
         IRepository<users> usersRespository,
         IRepository<supplier> supplier,
         IRepository<personal_details> personal_details,
         IRepository<receiving_site> receiving_site,
         IRepository<shopping_cart> shopping_cart
         )
        {
            _configuration = configuration;
            _tokenParameter = _configuration.GetSection("tokenParameter").Get<TokenParameter>();

            _usersRespository = usersRespository;
            _supplier = supplier;
            _personal_details = personal_details;
            _receiving_site = receiving_site;
            _shopping_cart = shopping_cart;
        }



        // 添加个人信息
        [HttpPost]
        public dynamic addPersonalDetails(PersonalDetailsModel model)
        {
            var userId = model.UserId;
            var CPN = model.CPN;
            var sex = model.Sex;

            var personalDetails = new personal_details
            {
                UserId = userId,
                CPN = CPN,
                Sex = sex
            };
            _personal_details.Insert(personalDetails);

            var res = new
            {
                Code = 1000,
                Data = personalDetails,
                Msg = "添加个人信息成功"
            };
            return JsonHelper.Serialize(res);

        }



        // 根据用户Id查询个人信息
        [HttpGet("{userId}")]
        public dynamic selPersonalDetails(int userId)
        {
            var personalDetails = _personal_details.Table.Where(x => x.IsDeleted == false && x.UserId == userId).OrderByDescending(x => x.CreatedTime).ToList().FirstOrDefault();
            var res = new
            {
                Code = 1000,
                Data = personalDetails,
                Msg = "查询个人信息成功"
            };
            return JsonHelper.Serialize(res);
        }





        // # ======================================================================================
        // #       收货地址
        // # ======================================================================================


        // 添加收货地址
        [HttpPost, Route("add_receiving_site")]
        public dynamic addReceivingSite(PersonalDetailsModel model)
        {
            var site = model.Site;
            var userId = model.UserId;

            var receivingSite = new receiving_site
            {
                site = site,
                userId = userId
            };
            _receiving_site.Insert(receivingSite);

            var res = new
            {
                Code = 1000,
                Data = receivingSite,
                Msg = "添加收货地址成功"
            };
            return JsonHelper.Serialize(res);
        }

        // 根据用户Id修改收货地址
        [HttpPost, Route("up_receiving_site/{userId}")]
        public dynamic upReceivingSite(int userId, PersonalDetailsModel model)
        {
            var site = model.Site;

            var receivingSite = _receiving_site.Table.Where(x => x.userId == userId && x.IsDeleted == false).ToList().FirstOrDefault();
            receivingSite.site = site;
            _receiving_site.Update(receivingSite);


            var res = new
            {
                Code = 1000,
                Data = receivingSite,
                Msg = string.Format("修改用户id为{0}收货地址成功", userId)
            };
            return JsonHelper.Serialize(res);

        }

        // 根据收货地址Id删除收货地址
        [HttpPost, Route("del_receiving_site/{siteId}")]
        public dynamic delReceivingSite(int siteId)
        {
            var receivingSite = _receiving_site.GetById(siteId);
            receivingSite.IsDeleted = true;
            _receiving_site.Update(receivingSite);


            var res = new
            {
                Code = 1000,
                Data = receivingSite,
                Msg = string.Format("删除id为{0}收货地址成功", siteId)
            };
            return JsonHelper.Serialize(res);
        }

        // 根据用户id查询某个用户的所有收货地址
        [HttpGet, Route("sel_all_site/{userId}")]
        public dynamic selAllSite(int userId)
        {
            var allSite = _receiving_site.Table.Where(x => x.IsDeleted == false && x.userId == userId).OrderByDescending(x => x.CreatedTime).ToList();

            var res = new
            {
                Code = 1000,
                Data = allSite,
                Msg = string.Format("查询用户id为{0}的所有收货地址成功", userId)
            };
            return JsonHelper.Serialize(res);
        }



        // # ======================================================================================
        // #       购物车
        // # ======================================================================================

        // 购物车添加商品
        [HttpPost, Route("add_shopping_cart")]
        public dynamic addShoppingCart(ShoppingCartModel model)
        {
            var userId = model.userId;
            var commodityId = model.commodityId;
            var propertyVel = model.propertyVel;
            var quantity = model.Quantity;
            var money = model.Money;

            if (userId != 0 && commodityId != 0)
            {
                var shoppingCart = new shopping_cart
                {
                    userId = userId,
                    commodityId = commodityId,
                    propertyVel = propertyVel,
                    Quantity = quantity,
                    Money = money
                };
                _shopping_cart.Insert(shoppingCart);

                var res = new
                {
                    Code = 1000,
                    Data = shoppingCart,
                    Msg = "添加购物车成功"
                };
                return JsonHelper.Serialize(res);
            }
            else
            {
                var res = new
                {
                    Code = 1001,
                    Data = "添加购物车失败，用户id和商品id不能为空",
                    Msg = "添加购物车失败，用户id和商品id不能为空"
                };
                return JsonHelper.Serialize(res);
            }


        }

        // 根据购物车Id删除购物车商品
        [HttpPost, Route("del_shopping_cart/{id}")]
        public dynamic delShoppingCart(int id)
        {
            var delShoppingCart = _shopping_cart.GetById(id);

            if (delShoppingCart != null)
            {
                delShoppingCart.IsDeleted = true;
                _shopping_cart.Update(delShoppingCart);

                var res = new
                {
                    Code = 1000,
                    Data = delShoppingCart,
                    Msg = string.Format("删除购物车商品ID为{0}的商品成功", id)
                };
                return JsonHelper.Serialize(res);
            }
            else
            {
                var res = new
                {
                    Code = 1001,
                    Data = delShoppingCart,
                    Msg = string.Format("删除购物车商品ID为{0}的商品不存在，请重新尝试", id)
                };
                return JsonHelper.Serialize(res);
            }


        }

        // 根据用户Id查询购物车商品
        [HttpGet, Route("get_user_shopping/{userId}")]
        public dynamic getUserShopping(int userId)
        {
            var Id = _usersRespository.GetById(userId);
            if (Id != null)
            {
                var getUserShopping = _shopping_cart.Table.Where(x => x.IsDeleted == false && x.userId == userId).OrderByDescending(x => x.CreatedTime).ToList();

                var res = new
                {
                    Code = 1000,
                    Data = getUserShopping,
                    Msg = string.Format("用户ID为{0}的购物车商品成功", userId)
                };
                return JsonHelper.Serialize(res);
            }else
            {
                var res = new
                {
                    Code = 1001,
                    Data = string.Format("用户ID为{0}的购物车商品失败，用户不存在", userId),
                    Msg = string.Format("用户ID为{0}的购物车商品失败，用户不存在", userId)
                };
                return JsonHelper.Serialize(res);
            }

        }







    }
}